package com.heima.schedule.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import com.heima.schedule.service.impl.TaskServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class TaskSyncSchdule {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskServiceImpl taskService;

    @Autowired
    private CacheService cacheService;

    @Scheduled(cron = "0 0/5 * * * ?")
    public void dbToRedis(){
        log.info("数据库数据同步到缓存");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        QueryWrapper<Taskinfo> queryWrapper = new QueryWrapper<>();
        Date now = new Date();
        Date fiveMinutesAgo = new Date(now.getTime() + 5 * 60 * 1000);
        queryWrapper.le("execute_time",fiveMinutesAgo);
        List<Taskinfo> allTasks = taskinfoMapper.selectList(queryWrapper);
        if (allTasks!=null&&allTasks.size()>0){
            for (Taskinfo taskinfo : allTasks) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                taskService.addTaskToCache(task);
            }
        }

    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void redisZsetToList(){
        System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"))+"执行了定时任务");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        for (String futureKey : futureKeys) {
            String topicKey = ScheduleConstants.TOPIC+futureKey.split(ScheduleConstants.FUTURE)[1];
            Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
            if (!tasks.isEmpty()){
                cacheService.refreshWithPipeline(futureKey,topicKey,tasks);
                System.out.println("成功的将"+futureKey+"下的当前需要执行的任务数据刷新到"+topicKey+"下");
            }
        }
    }
    private void clearCache(){
        Set<String> futurekeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topickeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futurekeys);
        cacheService.delete(topickeys);
    }
}
